package com.hskj.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hskj.info.Imginfo;
import com.hskj.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UpdateController {

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name=uploadInfo.getName();
        String base64=uploadInfo.getBase64();
        //截取base64字符串编码
        String[] base64s= StrUtil.splitToArray(base64,"base64,");
        //切换为byte数组
        byte[] bytes= Base64.decode(base64s[1]);
        name= IdUtil.getSnowflakeNextIdStr()+"_"+name;
        //写入到本地文件夹中
        FileUtil.writeBytes(bytes,"D:/software/nginx-1.21.4/html/images/"+name);
        //返回
        return "http://www.hphs.com/images/"+name;
    }
    @GetMapping
    public List<Imginfo> getimg(){
        List<String> filenames= FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        List<Imginfo> collect=filenames.stream().map(item ->{
            return new Imginfo(item,"http://www.hphs.com/images/"+item);
        }).collect(Collectors.toList());
        return collect;
    }

}
